<?php
class UniqueMultiColumnValidator extends CValidator {
	public $errorAttributes = null;

	private $allowEmpty = false;
	public function setAllowEmpty($value) {
		$this->allowEmpty = $value;
	}
	public function getAllowEmpty() {
		return $this->allowEmpty;
	}

	private $caseSensitive = false;
	public function setCaseSensitive($value) {
		$this->caseSensitive = $value;
	}
	public function getCaseSensitive() {
		return $this->caseSensitive;
	}

	protected function validateAttribute($object, $attribute) {
		$attributes = null;
		$criteria = array(
			'condition' => ''
		);
		//if (is_string($attributes))
		$attributes = preg_split('/[\s\+]+/', $this->attributes[0], -1, PREG_SPLIT_NO_EMPTY);

		foreach ($attributes as $attribute) {
			$value = $object->$attribute;
			if ($this->allowEmpty && ($value === null || $value === ''))
				return;
			$column = $object->getTableSchema()->getColumn($attribute);
			if ($column === null)
				throw new CException(
					Yii::t('yii', '{class} does not have attribute "{attribute}".',
						array(
							'{class}' => get_class($object),
							'{attribute}' => $attribute
						)));
			$columnName = $column->rawName;
			if ('' != $criteria['condition']) {
				$criteria['condition'] .= " AND ";
			}
			if ($value !== null) {
				$criteria['condition'] .= $this->caseSensitive ? "$columnName=:$attribute"
					: "LOWER($columnName)=LOWER(:$attribute)";
				$criteria['params'][':' . $attribute] = $value;
			}else{
				$criteria['condition'] .="$columnName IS NULL";
			}
		}

		if ($column->isPrimaryKey)
			$exists = $object->exists($criteria);
		else {
			// need to exclude the current record based on PK
			$criteria['limit'] = 2;
			$objects = $object->findAll($criteria);
			$n = count($objects);
			if ($n === 1) {
				if ('' == $object->getPrimaryKey()) {
					$exists = true;
				} else {
					$exists = $objects[0]->getPrimaryKey() !== $object->getPrimaryKey();
				}
			} else
				$exists = $n > 1;
		}
		if ($exists) {
			$message = '';
			$labels = $object->attributeLabels();
			foreach ($attributes as $attribute) {
				$message .= $labels[$attribute] . "+";
			}
			$message = substr($message, 0, -1);
			$message = $this->message !== null ? $this->message : "组合 ($message) 在系统中已经存在";
			$errorAttributes = $this->errorAttributes;
			if (empty($errorAttributes)) {
				$errorAttributes = $attributes;
			}
			foreach ($errorAttributes as $attribute) {
				$this->addError($object, $attribute, $message);
			}
		}
	}
}
?>
